//
//  PartProductView.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/6/20.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "PartProductView.h"
#import "ProductListCell.h"
#import "ProductListHeaderView.h"
#import "MTShopSingleModel.h"
#import "MTProductGroup.h"

#define cateLeftWidth 65

@interface PartProductView()<UITableViewDelegate,UITableViewDataSource>

proAssign NSInteger cateIndex;
proStrong NSArray *productGroupArray;

proAssign BOOL isSelectSlide;//是点击leftTableView，还是拖拽右边的滑动视图
proAssign BOOL isGestureEnd;//手势是否已经结束

@end

@implementation PartProductView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gestureStateBegan:) name:@"GestureRecognizerStateBegan" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gestureStateEnd:) name:@"GestureRecognizerStateEnded" object:nil];
        
        [self resetUI];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)resetUI {
    
    self.backgroundColor = [UIColor whiteColor];
    
    // ===== 分类视图
    //分类视图默认高度为可显示部分的高度
    self.categoryTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,cateLeftWidth, self.height-[[MTShopSingleModel sharedInstance] maxOffsetY]) style:UITableViewStyleGrouped];
    self.categoryTableView.dataSource = self;
    self.categoryTableView.delegate = self;
    self.categoryTableView.backgroundColor = [UIColor whiteColor];
    self.categoryTableView.tableFooterView = [UIView new];
    self.categoryTableView.separatorColor = kColorLineColor;
    self.categoryTableView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.categoryTableView];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(cateLeftWidth-0.5, 0, 0.5, self.height)];
    line.backgroundColor = kColorLineColor;
    [self.categoryTableView addSubview:line];
    
    // ===== 列表视图
    self.productTableView = [[UITableView alloc]initWithFrame:CGRectMake(cateLeftWidth, 0,self.width-cateLeftWidth, self.height) style:UITableViewStylePlain];
    self.productTableView.dataSource = self;
    self.productTableView.delegate = self;
    self.productTableView.backgroundColor = [UIColor whiteColor];
    self.productTableView.tableFooterView = [UIView new];
    self.productTableView.separatorColor = kColorLineColor;
    self.productTableView.showsVerticalScrollIndicator = NO;
    self.productTableView.scrollEnabled = NO;//禁止滚动，列表视图将配置外层手势做内容便宜，已达到模拟滑动的效果
    [self.productTableView registerClass:[ProductListCell class] forCellReuseIdentifier:@"ProductListCell"];
    [self.productTableView registerClass:[ProductListHeaderView class] forHeaderFooterViewReuseIdentifier:@"ProductListHeaderView"];
    [self addSubview:self.productTableView];
}

- (void)superScrollViewDidScrollOffset:(CGFloat)offset {
    //分类视图作为一个与手势滑动无关独立的视图，但是页面高度要占满整个产品页面的显示区
    if (offset <= [[MTShopSingleModel sharedInstance] maxOffsetY]) {
        self.categoryTableView.height = self.height-[[MTShopSingleModel sharedInstance] maxOffsetY] + offset;
    }
}

#pragma mark ---通知方法
- (void)gestureStateBegan:(NSNotification *)not{
    
    BOOL isMore = self.productTableView.contentOffset.y >= (self.productTableView.contentSize.height - self.productTableView.height);
    if (isMore) {
        self.isGestureEnd = NO;
    }
    //手动拖拽
    self.isSelectSlide = NO;
}

- (void)gestureStateEnd:(NSNotification *)not{
    
    //    手势已经结束
    BOOL isMore = self.productTableView.contentOffset.y > (self.productTableView.contentSize.height - self.productTableView.height);
    if (isMore) {
        //如果滑动的偏移量超出最大的内容范围
        CGFloat between = self.productTableView.contentOffset.y - (self.productTableView.contentSize.height - self.productTableView.height);
        if (between >= 70) {
            self.isGestureEnd = YES;
        }
    }
}

#pragma mark -
#pragma mark UIScrollView delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    //当拖拽_leftTabView时候，应该停止右视图的手势,停止滚动
    [self.shopSuperView removeBehaviors];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView != self.categoryTableView) {
        NSArray *array;
        array = self.productTableView.indexPathsForVisibleRows;
        if (array.count > 0) {
            //1:找到indexPath
            NSIndexPath *indexPath = array[0];
            //2:可见的第一个section位置
            NSInteger section = indexPath.section;
            //3:
            if (!_isSelectSlide) {
                //只有拖拽的时候，才执行该方法
                [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:section inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            }
        }
    }
}

#pragma mark -
#pragma mark UITableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView == self.categoryTableView) {
        return 1;
    } else {
        MTProductCategory *category = [MTShopSingleModel sharedInstance].categoryArray[self.cateIndex];
        return category.productGroupList.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.categoryTableView) {
        return [MTShopSingleModel sharedInstance].categoryArray.count;
    } else {
        MTProductCategory *category = [MTShopSingleModel sharedInstance].categoryArray[self.cateIndex];
        MTProductGroup *group = category.productGroupList[section];
        return group.productList.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.categoryTableView) {
        return 44;
    }else{
        return [ProductListCell cellHeight];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.productTableView) {
        return [ProductListHeaderView viewHeight];
    }else{
        return 0.01;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    return bgView;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (tableView == self.productTableView) {
        
        ProductListHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ProductListHeaderView"];
        
        MTProductCategory *category = [MTShopSingleModel sharedInstance].categoryArray[self.cateIndex];
        MTProductGroup *group = category.productGroupList[section];
        [headerView loadData:group.name];
        
        return headerView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.categoryTableView) {
        
        static NSString *reuseID = @"categoryCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            UILabel *titleLab = [Utils genLabelWithFrame:CGRectMake(0,0, cateLeftWidth, 50) textAlign:NSTextAlignmentCenter fontSize:13 textColor:kColorBlack];
            titleLab.tag = 10;
            [cell.contentView addSubview:titleLab];
            
            UIView *selectView = [[UIView alloc]initWithFrame:cell.frame];
            selectView.backgroundColor = [UIColor whiteColor];
            cell.selectedBackgroundView = selectView;
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0 );
        }
        UILabel *titleLab = [cell.contentView viewWithTag:10];
        
        MTProductCategory *category = [MTShopSingleModel sharedInstance].categoryArray[indexPath.row];
        titleLab.text = category.name;
        if (indexPath.row == self.cateIndex) {
            [self.categoryTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
        cell.backgroundColor = kColorBgColor;
        return cell;
        
    } else {
        
        ProductListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductListCell" forIndexPath:indexPath];
        
        MTProductCategory *category = [MTShopSingleModel sharedInstance].categoryArray[self.cateIndex];
        MTProductGroup *group = category.productGroupList[indexPath.section];
        MTProduct *product = group.productList[indexPath.row];
        
        [cell loadData:product];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.categoryTableView == tableView) {
        
        self.isSelectSlide = YES;
        
        self.cateIndex = indexPath.row;
        
        [self.categoryTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        
        [self.productTableView reloadData];
        [self.productTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

@end
